package com.perfma.xtest.download;

import java.io.*;
import java.net.URL;

/**
 * @author: junhui.si
 * @date: 2020-08-28 16:19
 **/
public class DownloadTest {


    public static void main(String[] args) {
        String baseUrl = "https://book.yunzhan365.com/vppw/xyvv/files/mobile/$$.jpg";
        String basePath = "/Users/sijunhui/Downloads/down/";
        for (int i = 1; i < 89; i++) {
            String url = baseUrl.replace("$$", i + "");
            try {
                downloadImage(url, basePath + i + ".jpg");
            } catch (Exception e) {
                System.out.println("错误：" + i);
            }
        }
    }

    public static void downloadImage(String fileUrl, String filePath) {
        if (fileUrl != null) {
            DataInputStream fis = null;
            BufferedInputStream bis = null;
            OutputStream outputStream = null;
            BufferedOutputStream out = null;

            try {
                File file = new File(filePath);
                outputStream = new FileOutputStream(file, true);
                out = new BufferedOutputStream(outputStream);
                URL url = new URL(fileUrl);
                fis = new DataInputStream(url.openStream());
                byte[] buffer = new byte[1024];
                bis = new BufferedInputStream(fis);
                int i = bis.read(buffer);
                while (i != -1) {
                    out.write(buffer, 0, i);
                    i = bis.read(buffer);
                }

            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                if (bis != null) {
                    try {
                        bis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (out != null) {
                    try {
                        out.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
                if (outputStream != null) {
                    try {
                        outputStream.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}
